﻿/*
todo:  
6、增加压缩选项
*/ 
function GIMUploader() {
    this.Uploader = null;
    this.maxThread = 5;
    this.registered = false;
    this.receiverUrl = "http://localhost:9090/GIMUploaderReceiver.ashx";
    this.activeXPackageUrl = "GIMUploader.rar";
    this.pattern = "*.*";
    this.maxFileSize = 0;
    this.maxFileCount = 0;
    this.autoUpload=false;
    this.fileList = new Array();
    this.name = "";
    this.isUploading = false;
    //每个文件开始上传时回调函数
    this.onBeforeUpload = function(file) { } 
    //每个文件完成时回调函数
    this.onSingleComplate = function(file) {} 
    //所有文件上传完成回调函数
    this.onComplate = function(uploader) {}
    //上传数据状态变化时回调函数
    this.onChange = function(file) { }
    //当文件被删除时触发
    this.onRemoveUpload = function(file) { }
    
    
    this.multiUpload = true;

    this.newVersion = 1.00128; //最新控件版本号
    this.needUpdate = true; //是否强制升级

    this.init = function() {
        try {
            this.Uploader = new ActiveXObject("GIMUploader.ActiveX");

            if (this.needUpdate) {
                curVersion = this.Uploader.version;
                newVersion = this.newVersion; 
                if (curVersion) {
                    curVersion = Number(curVersion);
                    if (newVersion > curVersion) {
                        alert("控件已升级，请先下载最新版本！");
                        document.write("　<a href=" + this.activeXPackageUrl + ">下载GIMUploader控件</a>");
                        return;
                    }
                }
                else {
                    alert("控件已升级，请先下载最新版本！");
                    document.write("　<a href=" + this.activeXPackageUrl + ">下载GIMUploader控件</a>");
                    return;
                }
            }

            this.multiUpload = (this.maxFileCount != 1);
            this.Registered = true;
            this.Uploader.Receiver = this.receiverUrl;
            this.Uploader.MaxFileSize = this.maxFileSize;
            this.Uploader.Pattern = this.pattern;
            this.Uploader.MultiFile = this.multiUpload;
            initHtml(this.name, this.multiUpload);

            eval("$(window).unload(function() { " + this.name + ".stopAllUploadFile() });");
 
        }
        catch (ex) {
            this.Registered = false;
            if (!hasDotNetFramework(2)) {
                alert("先安装 .Net Framework 2.0！");
                document.write("<a href=http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5&displaylang=zh-cn target=_blank>下载.Net Framework2.0</a>");
                return;
            }
            if (confirm("尚未安装服务新干线大文件上传控件，是否现在安装？")) {
                window.location.href = this.activeXPackageUrl;
            }
            else {
                document.write("　<a href=" + this.activeXPackageUrl + ">下载GIMUploader控件</a>");
            }
        }
    }

    this.addFileList = function(file) {
    if (this.multiUpload) {
            this.fileList.con
            if (file.State == "Added") { this.fileList[this.fileList.length] = file; }
            if (file.State != "Uploading" && file.State != "Complated") this.flushToPage(file);
        }
        else {
            if (this.fileList.length > 0 && this.fileList[0]) {
                var file0 = this.fileList[0];
                this.Uploader.Remove(file0.FileName);
                delete (this.fileList[0]);
                $('#GIMUploader_FileItem_' + file0.GUID).remove();
            }
            if (file.State == "Added") this.fileList[0] = file;
            if (file.State != "Uploading" && file.State != "Complated") this.flushToPage(file);
        }
    }

    this.doUpload = function() {
        while (this.uploadNext() && this.getCurrentThread() < this.maxThread) { continue; }
     }

     this.flushToPage = function(file) {
         if (file && file.GUID) {
             var guid = file.GUID;
             var progress = Math.round(file.UploadedSize / file.FileSize * 10000) / 100;
             var uploadsize = formatFileSize(file.UploadedSize);
             if ($('#GIMUploader_FileItem_' + guid).length > 0) {
                 $('#Speed_' + guid).html("<span>已上传:" + uploadsize + "</span>&nbsp;&nbsp;<span>" + progress + "%</span>");
                 switch (file.State) {
                     case "Uploading":
                         setUploadingState(file, progress);
                         break;
                     case "Error":
                         setErrorState(file);
                         break;
                     case "Stoped":
                         setStopedState(file);
                         break;
                     case "Waiting":
                         setWaitingState(file);
                         break;
                     case "Complated":
                         setComplatedState(file);
                         this.onSingleComplate(file);
                         this.doUpload();
                         if (!this.multiUpload) {
                             $('#' + this.name + 'ChooseButton').removeAttr("disabled");
                             $('#remove_' + file.GUID).show();
                         }
                         break;
                 }
             }
             else {
                 addFileItemToPage(file, this.name);
             }
         }
     }

    this.getCurrentThread = function() {
        var j = 0;
        for (var i = 0; i < this.fileList.length; i++) {
            var file = this.fileList[i];
            if (file && file.State == "Uploading") {
                j++;
            }
        }
        return j;
    }

    this.uploadNext = function() {
        for (var i = 0; i < this.fileList.length; i++) {
            var file = this.fileList[i];
            if (file && file.State == "Added") {

                this.fileList[i] = eval(this.Uploader.UploadSingleFile(file.FileName));

                if (!this.isUploading) {
                    setTimeout("eval('" + this.name + "').uploaderWatcher(eval('" + this.name + "'))", 1000);
                }
                this.isUploading = true;
                this.onBeforeUpload(this.fileList[i]);
                return true;
            }
        }
        return null;
    }
    
    this.getFileHash=function(file){
        return this.Uploader.GetFileContetHash(file);
    }

    this.getCurrentFileCount = function() {
        var j = 0;
        for (var i = 0; i < this.fileList.length; i++) {
            var file = this.fileList[i];
            if (file) {
                 j++;
            }
        }
        return j;
    }

    this.stopAllUploadFile = function() {
        this.Uploader.StopUploadAll();
    }

    this.uploaderWatcher = function() {
        var needWatcher = false;
        for (var i = 0; i < this.fileList.length; i++) {
            var file = this.fileList[i];
            if (file) {
                file = eval(this.Uploader.Get(file.FileName));
                if (file && file.GUID) {
                    this.fileList[i] = file;
                    this.flushToPage(file);
                    this.onChange(file);
                    if (file.State == "Uploading" || file.State == "Stoped")
                        needWatcher = true;
                    if (file.State == "Complated")
                        this.Uploader.Remove(file.FileName);
                }
            }
        }
        if (needWatcher) {
            this.isUploading = true;
            setTimeout(this.name + ".uploaderWatcher()", 1000);
        }
        else {
            this.isUploading = false;
            this.onComplate(this);
        }
    }

    this.chooseFile = function() {
        var files = this.Uploader.ChooseFile();
        if (files.length > 0) {
            var fileArray = files.split('|');

            var curCount = this.getCurrentFileCount();
            if (this.multiUpload && this.maxFileCount > 0 && curCount + fileArray.length > this.maxFileCount) {
                alert("最多只允许上传 " + this.maxFileCount + " 个文件，请重新选择！");
                return;
            }

            for (var i = 0; i < fileArray.length; i++) {
                var file = new GIMUploaderFile();
                file = eval(this.Uploader.Add(fileArray[i]));
                if (file && file.GUID) {
                    if (file.ErrorInfo == 'OverSize') {
                        alert("文件" + file.ShortName + "的大小超出了" + this.maxFileSize + "K的限制，无法上传！");
                    }
                    else {
                        this.addFileList(file);
                        //如果是单文件，直接上传
                        if (!this.multiUpload || this.autoUpload) {
                            this.disabled = true;                 
                            $('#GIMUploaderTop').hide();                            
                            this.startUpload();
                        }
                    }
                }
            }
        }
    }

    this.startUpload = function() { 
        this.doUpload();
        if (!this.multiUpload) {
            $('#'+this.name+'ChooseButton').attr("disabled", "true");
        }
    }

    this.stopUpload = function(guid) {
        for (var i = 0; i < this.fileList.length; i++) {
            var file = this.fileList[i];
            if (file && file.GUID == guid) {
                if (file.State == "Stoped") {
                    $('#stop_' + guid).text('暂停');
                    this.Uploader.UploadSingleFile(file.FileName);
                    if (!this.multiUpload) {
                        $('#' + this.name + 'ChooseButton').attr("disabled", "true");
                    }
                }
                else if (file.State == "Added" || file.State == "Waitting") {
                    this.removeUpload(guid);
                }
                else {
                    $('#stop_' + guid).text('继续');
                    this.Uploader.StopUpload(file.FileName);
                    if (!this.multiUpload) {
                        $('#' + this.name + 'ChooseButton').removeAttr("disabled");
                    }
                }
                break;
            }
        }
    }

    this.removeUpload = function(guid) {

    if (!confirm("确实要删除吗？")) return false;
        
        for (var i = 0; i < this.fileList.length; i++) {
            var file = this.fileList[i];
            if (file && file.GUID == guid) {
                if (file.State == "Uploading") { alert('文件正在上传，无法删除，请暂停后再进行删除！'); return false; }
                this.onRemoveUpload(file);
                this.Uploader.Remove(file.FileName);
                this.fileList.splice(i, 1);
                $('#GIMUploader_FileItem_' + file.GUID).remove();
                //$('#remove_' + file.GUID).hide();
                if (!this.multiUpload) {
                    $('#GIMUploaderTop').show();
                    $('#' + this.name + 'Content').hide();
                }
            }
        }
    }

    function hasDotNetFramework(baseVersion) {
        if (typeof baseVersion == "undefined") baseVersion = 1;
        var userAgent = navigator.userAgent.toLowerCase();
        for (var i = baseVersion; i < 10; i++) {
            if (userAgent.indexOf('.net clr ' + i + '.') > -1) {
                return true;
            }
        }
        return false;
    }

    function initHtml(name, multi) { 
    
        document.write('<div id="GIMUploaderContainer">');
        document.write('<div id="GIMUploaderTop"><input type="button" id="' + name + 'ChooseButton" onclick="' + name + '.chooseFile()" value="浏览..." /></div>');
        document.write('<div id="' + name + 'Content"></div>');
        document.write('<div id="GIMUploaderFoot"><input type=button id=' + name + 'UploadButton onclick="' + name + '.startUpload()" value="开始上传" /> </div>');
        document.write('</div>');

        document.write('<style>');
        document.write('#GIMUploaderContainer{padding:10px;width:400px;background:#ececec;font-size:9pt;}');
        document.write('#GIMUploaderTop{height:20px;margin:3px 0px;}');
        document.write('#'  +name + 'Content{height:' + (multi ? '200px' : '65px') + ';overflow-y:' + (multi ? 'scroll' : 'hidden') + ';border:1px solid #ccc;background:#fff;display:' + (multi ? 'block' : 'none') + ';}');
        document.write('#GIMUploaderFoot{height:20px;margin:3px 0px;text-align:right;display:' + (multi ? 'block' : 'none') + '}');
        document.write(".GIMUploaderFileItem{height:50px;border-bottom:1px solid #ccc;margin:5px 0px 0px 5px;padding:5px;}");
        document.write(".GIMUploaderFileItem .fileName{height:15px;font-weight:bold;width:80%;overflow:hidden;}");
        document.write(".fileSpeed{margin-top:5px;color:#006699}");
        document.write(".Progress_Container{height:10px;border:1px solid #ccc;padding:1px;font-size:10px;display:none;text-align:left;width:100%}");
        document.write(".progress{background:#0f0;width:1px;height:10px;font-size:10px;}");
        document.write(".statetip{color:#999;padding-left:20px;width:300px;margin:5px 0px 5px 0px;}");
        if (eval(name+".autoUpload")) {
            document.write("#GIMUploaderFoot{display:none}");
            document.write("#" + name + 'Content{height:1px;overflow-y:visible;display:none}');
        }
        document.write('</style>');
    }

    function formatFileSize(size) {
        var s = size / 1024;
        if (s > 1024) {
            s = s / 1024;
            return Math.round(s*100)/100 + "M";
        }

        if (s < 1) {
            return size + "B"
        }
        else {
            return Math.round(s) + "K";
        } 
    }

    function addFileItemToPage(file,name) {
        var guid = file.GUID;
        var fileItem = "<div id=GIMUploader_FileItem_" + file.GUID + " class=GIMUploaderFileItem>";
        fileItem += " <div id=FileName_" + guid + " class=fileName style=float:left>" + file.ShortName + "</div>";
        fileItem += "<div><span><a id=stop_" + guid + " href='javascript:;' onclick=" + name + ".stopUpload('" + guid + "')>取消</a>&nbsp;<a id=remove_" + guid + " href='javascript:;' onclick=" + name + ".removeUpload('" + guid + "')>删除</a>&nbsp;</span></div>";
        fileItem += "<div id=GIMUploader_State_" + guid + " class=statetip>正在等待上传...</div>";
        fileItem += "<div class=Progress_Container id='progress_c_" + guid + "'><div class=progress id=Progress_" + guid + ">&nbsp;</div></div>";
        fileItem += " <div id=Speed_" + guid + " class=fileSpeed><span>已上传:0K</span>&nbsp;&nbsp;<span>0%</span></div>";
        fileItem += "</div>";
        $('#' + name + 'Content').show();
        $('#' + name + 'Content').append(fileItem);
    }

    function setUploadingState(file, progress) {
        var guid = file.GUID;
        $('#stop_' + guid).text('暂停');
        $('#GIMUploader_State_' + guid).css("display", "none");
        $('#progress_c_' + guid).css("display", "block");
        $('#Progress_' + guid).css("background", "#0f0");
        $('#Progress_' + guid).css("width", progress + "%"); 
    }

    function setErrorState(file) {
         var guid = file.GUID;
        $('#stop_' + guid).text('重试');
        $('#GIMUploader_State_' + guid).css("display", "block");
        $('#GIMUploader_State_' + guid).css("color", "red");
        $('#GIMUploader_State_' + guid).text("上传过程中出现错误，你可以尝试重试...")
        $('#progress_c_' + guid).css("display", "none");
     }

    function setStopedState(file) {
        var guid = file.GUID;
        $('#stop_' + guid).text('继续');
        $('#GIMUploader_State_' + guid).css("display", "none");
        $('#progress_c_' + guid).css("display", "block");
        $('#Progress_' + guid).css("background", "#eee");
      }

    function setWaitingState(file) {
        var guid = file.GUID;
        $('#stop_' + guid).text('取消');
        $('#GIMUploader_State_' + guid).css("display", "block");
        $('#progress_c_' + guid).css("display", "none");
    }

    function setComplatedState(file) {
        var guid = file.GUID;
        $('#stop_' + guid).text('');
        $('#GIMUploader_State_' + guid).css("display", "block");
        $('#GIMUploader_State_' + guid).css("color", "green");
        $('#GIMUploader_State_' + guid).css("font-weight", "bold");
        $('#GIMUploader_State_' + guid).text('已完成');
        $('#progress_c_' + guid).css("display", "none");
    } 
}

function GIMUploaderFile() {
    this.FileName = "";
    this.ShortName = "";
    this.FileSize = 0;
    this.UploadSize = 0;
    this.GUID = "";
    this.State = "";
} 